package com.test.gpa.security.Impl;

import com.test.gpa.domain.User;
import com.test.gpa.repostitory.UserSqlRepository;
import com.test.gpa.security.config.RedisCache;
import com.test.gpa.security.config.ResponseResult;
import com.test.gpa.security.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * 登录的业务层
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    UserSqlRepository userSqlRepository;

    @Override
    public ResponseResult login(User user) {
        //当在页面中输入用户名和密码之后首先会进入到UsernamePasswordAuthenticationToken验证(Authentication)，
        //然后生成的Authentication会被交由AuthenticationManager来进行管理
        System.out.println("开始效验密码");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);//验证密码
        System.out.println("获取用户信息");
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();//Principal用户主体信息
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);//创建jwt
        //authenticate存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);//用户信息集合
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登陆成功", map);
    }

    @Override
    public ResponseResult logout(Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser=null;
        try{
        loginUser = (LoginUser) authentication.getPrincipal();
        }
        catch (Exception e){
            return new ResponseResult<>(501,"未登录",null);
        }
        Long userid = loginUser.getUser().getId();
        System.out.println("开始退出,获取authentication"+loginUser.getUser().getUserName());
        if (Objects.isNull(userid)) {
            userid =  id;
        }
        boolean b = redisCache.deleteObject("login:" + userid);
        if (b) {
            System.out.println("退出成功");
            return new ResponseResult(200, "退出成功");

        } else{
            System.out.println("退出失败");
            return new ResponseResult(500, "退出失败");}

    }
}
